package telepasea.app;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Security {
	public static String secureKey = "0123456789abcdef";
		
	public static String encrypt(String originText) throws Exception{
		SecretKeySpec skeySpec = new SecretKeySpec(secureKey.getBytes(), "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		
		byte[] encryptedData = cipher.doFinal(originText.getBytes());
		
		return bytesTohex(encryptedData);
	}
		
	public static String decrypt(String encryptedText) throws Exception{
		SecretKeySpec skeySpec = new SecretKeySpec(secureKey.getBytes(), "AES");
	    Cipher cipher = Cipher.getInstance("AES");
	    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
	
	    byte[] decryptedData = cipher.doFinal(hexTobytes(encryptedText));

	    return new String(decryptedData);
	}
		
	public static String bytesTohex(byte[] bytes){
        if(bytes == null || bytes.length == 0)		return null;
        
        StringBuffer sb = new StringBuffer(bytes.length * 2);
        String hexNum;
        
        int i;
        for(i = 0; i < bytes.length; i++){
            hexNum = "0" + Integer.toHexString(0xff & bytes[i]);
            sb.append(hexNum.substring(hexNum.length() - 2));
        }
        
        return sb.toString();
    }
	
	public static byte[] hexTobytes(String hex){
		 if(hex == null || hex.length() == 0)		return null;
		 
		 byte[] bytes = new byte[hex.length() / 2];
		 
		 int i;
		 for (i = 0; i < bytes.length; i++) {
			 bytes[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
		 }
		 
		 return bytes;
	}
}

